package com.atguigu.datastream.day08;

import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink02_OperatorState_BroadcastState
 * Package: com.atguigu.day08
 * Description:
 *
 * @Author ChenJun
 * @Create 2023/4/15 16:39
 * @Version 1.0
 */
public class Flink02_OperatorState_BroadcastState {
    public static void main(String[] args) throws Exception {

        //1. 创建流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2. 创建两条流
        DataStreamSource<String> localStream = env.socketTextStream("localhost", 9999);
        DataStreamSource<String> hadoopStream = env.socketTextStream("hadoop102", 9999);

        //3. 创建广播本地流
        MapStateDescriptor<String, String> mapState = new MapStateDescriptor<>("mapState", String.class, String.class);
        BroadcastStream<String> broadcast = localStream.broadcast(mapState);

        //4. 链接广播流和hadoop流
        BroadcastConnectedStream<String, String> connect = hadoopStream.connect(broadcast);

        //5. 通过local流中的数据控制hadoop流中的逻辑
        SingleOutputStreamOperator<String> result = connect.process(new BroadcastProcessFunction<String, String, String>() {
            @Override
            public void processElement(String value, BroadcastProcessFunction<String, String, String>.ReadOnlyContext ctx, Collector<String> out) throws Exception {
                //获取广播状态
                ReadOnlyBroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapState);
                String swith = broadcastState.get("swith");
                //通过广播状态里面的值来控制业务逻辑
                if ("1".equals(swith)) {
                    out.collect("执行加法逻辑。。。。。");
                } else if ("2".equals(swith)) {
                    out.collect("执行乘法逻辑。。。。。");
                } else {
                    out.collect("执行其他逻辑。。。。。");
                }

            }

            @Override
            public void processBroadcastElement(String value, BroadcastProcessFunction<String, String, String>.Context ctx, Collector<String> out) throws Exception {
                //获取广播状态
                BroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapState);
                broadcastState.put("swith", value);
            }
        });

        result.print();

        env.execute();
    }
}
